--[[    兑换
]]
local ExchangeLayerNew = class("ExchangeLayerNew", function(scene)
	local newLayer = display.newLayer(cc.c4b(0, 0, 0, 180))
	return newLayer
end)
local utils = appdf.req(appdf.EXTERNAL_SRC .. "Utils")
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. 'ExternalFun')
local AlipayLayer = appdf.req(appdf.CLIENT_SRC .. 'plaza.views.layer.plaza.BindAlipayLayer')
local BindBankLayer = appdf.req(appdf.CLIENT_SRC .. 'plaza.views.layer.plaza.BindBankLayer')
local LEFT_GOLD = 10000  --至少留10

function ExchangeLayerNew:ctor(_scene)
    self._scene = _scene
	ExternalFun.registerNodeEvent(self)
    self.currentPage = 1
    self.exchangeRecords = {}
	self.records = {}
    self:loadCSB()
    self:initUI()
	
	
	if GlobalUserItem.URLconfig.exchangemethodurl then
		utils.getExchangeInfo({},function (recdata)
				GlobalUserItem.ExchangeInfo = recdata
		end)
	end
	
end
function ExchangeLayerNew:getserverConfig()
	return self._scene:getApp()._serverConfig
end
function ExchangeLayerNew:loadCSB()
	local root,rootnode = ExternalFun.loadCSB("duihuang/duihuanLayer.csb", self)
	self.csbNode = root
	self.img_exchangeBg = root:getChildByName("img_exchangebg")
	ExternalFun.FixTopUI(root)
	self.csbNode:setPositionY((display.height-750)/2)
	local bg = self.img_exchangeBg
	self.btn_close = bg:getChildByName("btn_close")
	self.btn_listview = bg:getChildByName("btn_listview")
	self.btn_aplipayexchange = self.btn_listview:getChildByName("btn_alipayexchange")
	self.btn_bankexchange = self.btn_listview:getChildByName("btn_bankexchange")
	self.btn_exchangerecord = self.btn_listview:getChildByName("btn_exchangerecord") 


	
    self.ly_alipay = bg:getChildByName("layer_alipay")
	self.ly_alipay:setVisible(false)
	self.btn_aplipayexchange:setEnabled(false)
	local ali = self.ly_alipay
	self.ali_btn_sure = ali:getChildByName("btn_sure") 
	self.ali_txt_balance = ali:getChildByName('txt_balance')
	self.ali_txt_tips = ali:getChildByName("txt_tips_2")
	self.ali_tf_exchangemount = ali:getChildByName("new_exchange_edit_bg_7"):getChildByName("tf_exchangemount")
	self.ali_btn_clear = ali:getChildByName("btn_clear")
	self.ali_slider_percent = ali:getChildByName("slider_percent")
	self.ali_btn_max = ali:getChildByName("btn_maxvalue")
    self.ali_tf_cardnu = ali:getChildByName("new_exchange_edit_bg_8"):getChildByName("tf_alicount")
    self.ali_tf_cardnu:setEnabled(false)
	self.ali_btn_bindali = ali:getChildByName("btn_bindalipay")
	
	self.ly_bank = bg:getChildByName("layer_bank")
	self.ly_bank:setVisible(false)
	local bk = self.ly_bank
	self.bk_btn_sure = bk:getChildByName("btn_sure")
	self.bk_txt_balance = bk:getChildByName("txt_balance")
	self.bk_txt_tips = bk:getChildByName("txt_tips_2")
	self.bk_tf_exchangemount = bk:getChildByName("new_exchange_edit_bg_7"):getChildByName("tf_exchangemount")
	self.bk_btn_clear = bk:getChildByName("btn_clear")
	self.bk_slider_percent = bk:getChildByName("slider_percent")
	self.bk_btn_max = bk:getChildByName("btn_maxvalue")
    self.bk_tf_cardnu = bk:getChildByName("new_exchange_edit_bg_8"):getChildByName("tf_cardnu")
    self.bk_btn_bindcard = bk:getChildByName("btn_bindcard")
	self.ly_record = bg:getChildByName("layer_record")
	



	
	self.ly_recordDemo = root:getChildByName("ly_recordItem")
    self.btn_aplipayexchange:setTag(1)
    self.btn_bankexchange:setTag(2)
    self.btn_exchangerecord:setTag(3)
    local btncallback = function(ref,type)
        if type == ccui.TouchEventType.ended then
			ref:setScale(1)
			ExternalFun.playClickEffect()
            self:onButtonClicked(ref:getTag(),ref)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
        end
    end
    self.btn_close:addTouchEventListener(btncallback)
    self.btn_aplipayexchange:addTouchEventListener(btncallback)
    self.btn_bankexchange:addTouchEventListener(btncallback)
    self.btn_exchangerecord:addTouchEventListener(btncallback)
    self.ali_btn_sure:addTouchEventListener(btncallback)
    self.ali_btn_clear:addTouchEventListener(btncallback)
    self.ali_btn_max:addTouchEventListener(btncallback)
    self.ali_btn_bindali:addTouchEventListener(btncallback)
    self.bk_btn_sure:addTouchEventListener(btncallback)
    self.bk_btn_clear:addTouchEventListener(btncallback)
    self.bk_btn_max:addTouchEventListener(btncallback)
    self.bk_btn_bindcard:addTouchEventListener(btncallback)

    self:initEditControls()
    local events = {"exchangeRecords","EXCHANGE",}
   self.tb_listen = appdf.initListener(events,handler(self,self.customEventHandler),self)

    self.ali_slider_percent:addEventListener(function(sender, eventType)
        local real = self.ali_slider_percent:getPercent()
        local tg = math.floor(GlobalUserItem.lUserScore/ 1000 * real / 100  )
        self.ali_tf_exchangemount:setText(self:GoldMultiple(tg))
		self:refreshSubSlider(sender)
    end)
    
    self.bk_slider_percent:addEventListener(function(sender, eventType)
        local real = sender:getPercent()
        local tg = math.floor(GlobalUserItem.lUserScore/ 1000 * real / 100 )
        self.bk_tf_exchangemount:setText(self:GoldMultiple(tg)) 
		self:refreshSubSlider(sender)
    end)
    if string.len( string.ltrim(string.rtrim(GlobalUserItem.szAliPayAcccount)) ) > 0 and self.ali_btn_bindali then
		self.ali_btn_bindali:setVisible(false)  --bk_btn_bindcard
	end
	if string.len( string.ltrim(string.rtrim(GlobalUserItem.bankid)) ) > 0 and self.bk_btn_bindcard then
		self.bk_btn_bindcard:setVisible(false)  --ali_btn_bindali
	end
	self:initExchangeUI()
	ExternalFun.FixScaleUI(self.ly_record)
	ExternalFun.FixScaleUI(self.ly_bank)
	ExternalFun.FixScaleUI(self.ly_alipay)
end
function ExchangeLayerNew:initExchangeUI()
	if not GlobalUserItem.ExchangeInfo then
		return
	end
	local  tablenum = table.nums(GlobalUserItem.ExchangeInfo)
	if tablenum == 2 then
		GlobalUserItem.exchangeConfig.alipay = 1
		GlobalUserItem.exchangeConfig.unionpay = 1
	elseif GlobalUserItem.ExchangeInfo[1].account_type == 1 then
		GlobalUserItem.exchangeConfig.alipay = 1
		GlobalUserItem.exchangeConfig.unionpay = 0
	elseif GlobalUserItem.ExchangeInfo[1].account_type == 2 then	
		GlobalUserItem.exchangeConfig.alipay = 0
		GlobalUserItem.exchangeConfig.unionpay = 1
	end
end
function ExchangeLayerNew:initUI()
    self.ly_alipay:setVisible(true)
    self.ly_bank:setVisible(false)
    self.ly_record:setVisible(false)
    
  --[[  self.ali_tf_cardnu:setString(GlobalUserItem.szAliPayAcccount)
    self.bk_tf_cardnu:setString(GlobalUserItem.bankid)--]]
	utils:LabelSetString(self.bk_tf_cardnu,self:limitAcountLen(GlobalUserItem.bankid),"暂未绑定银行卡账号")
	utils:LabelSetString(self.ali_tf_cardnu,self:limitAcountLen(GlobalUserItem.szAliPayAcccount),"暂未绑定支付宝账号")
    GlobalUserItem.lUserScore = GlobalUserItem.lUserScore or 0
    local moneystr = ExternalFun.ChangeScore(GlobalUserItem.lUserScore ,2,',')
    local reslt = moneystr --moneystr.gsub(moneystr,',','/')

    self.ali_txt_balance:setString(reslt)
    self.bk_txt_balance:setString(reslt)
    

	self:refreshSubSlider(self.ali_slider_percent,0)
	self:refreshSubSlider(self.bk_slider_percent,0)
	local ex,_ = math.modf((GlobalUserItem.exchangeConfig.mingold or 100000 )/appdf.bili)
    local exchangeconfig = GlobalUserItem.exchangeConfig
	self.bk_txt_tips:setString("结算金额至少"..ex.."金币(结算收取"..(exchangeconfig.exchangeratio/10).."%的手续费，最低"..exchangeconfig.minratio/appdf.bili.."金币)")
	self.ali_txt_tips:setString("结算金额至少"..ex.."金币(结算收取"..(exchangeconfig.exchangeratio/10).."%的手续费，最低"..exchangeconfig.minratio/appdf.bili.."金币)")
	
	--self.btn_aplipayexchange
	--self.btn_bankexchange = 
	if exchangeconfig.alipay ~= 1 then
		self.ly_alipay:setVisible(false)
		self.btn_aplipayexchange:setVisible(false)
		self.btn_listview:removeItem(self.btn_listview:getIndex(self.btn_aplipayexchange))
		self.btn_aplipayexchange = nil
	end
	
	if exchangeconfig.unionpay == 1 and not self.ly_alipay:isVisible() then
		self.ly_bank:setVisible(true)
		self.btn_bankexchange:setVisible(true)
		self.btn_bankexchange:setEnabled(false)
	elseif  exchangeconfig.unionpay == 0 then
		self.ly_bank:setVisible(false)
		self.btn_bankexchange:setVisible(false)
		self.btn_listview:removeItem(self.btn_listview:getIndex(self.btn_bankexchange))
		self.btn_bankexchange = nil
	end
	local serverConfig = self:getserverConfig()
	if exchangeconfig.unionpay == 0 and  exchangeconfig.alipay == 0 then
		self.btn_exchangerecord:setEnabled(false)
		self.ly_record:setVisible(true)
		 self:showLayer(3)
	elseif serverConfig.exchangeorder ==  1 then
		self:showLayer(1)
	elseif serverConfig.exchangeorder ==  2 then	
		self:showLayer(2)
		self.btn_bankexchange:retain()
		self.btn_listview:removeItem(self.btn_listview:getIndex(self.btn_bankexchange))
		self.btn_listview:insertCustomItem(self.btn_bankexchange,0)
		self.btn_bankexchange:release()
	end
end
function ExchangeLayerNew:onExit()
	appdf.removeListener(self.tb_listen)
end
function ExchangeLayerNew:initEditControls()
    local aliszie = self.ali_tf_exchangemount:getContentSize()
    local bksize = self.bk_tf_exchangemount:getContentSize()
    local aliposx,aliposy = self.ali_tf_exchangemount:getPosition()
    local bkposx,bkposy = self.bk_tf_exchangemount:getPosition()
    self.ali_tf_exchangemount:removeFromParent()
    self.bk_tf_exchangemount:removeFromParent()
    self.ali_tf_exchangemount = nil 
    self.bk_tf_exchangemount = nil 
    self.ali_tf_exchangemount = ccui.EditBox:create(aliszie,ccui.Scale9Sprite:create(""))
        :setAnchorPoint(cc.p(0,0.5))
        :setPosition(cc.p(aliposx,aliposy))
	    :setFontSize(28)
	--    :setFontColor(cc.c3b(204,172,139))
	--    :setPlaceholderFontColor(cc.c3b(204,172,139))
	--    :setPlaceholderFontSize(27)
	    :setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
	    :setMaxLength(8)
        :setPlaceHolder("输入结算金额")

    self.ly_alipay:getChildByName("new_exchange_edit_bg_7"):addChild(self.ali_tf_exchangemount)
    self.ali_tf_exchangemount:registerScriptEditBoxHandler(function(event,editbox)
        if event == "return" then
            local nustr = editbox:getText()
            local money = tonumber(nustr)
			money = self:GoldMultiple(money)
            if money == nil or money < 0 then
                return 
            end
            if money * 1000 + LEFT_GOLD > GlobalUserItem.lUserScore then
                showToast(self, "账户金额不足", 1, cc.c3b(250, 0, 0))
				editbox:setText(math.floor((GlobalUserItem.lUserScore-LEFT_GOLD)/appdf.bili))
				local percent = 100
			   self:refreshSubSlider(self.ali_slider_percent,percent*100)
			else
				editbox:setText(money)
				local percent = money / ((GlobalUserItem.lUserScore-LEFT_GOLD) / 1000)
			   self:refreshSubSlider(self.ali_slider_percent,percent*100)
            end
			
        end
    end)
    
    self.bk_tf_exchangemount = ccui.EditBox:create(bksize,ccui.Scale9Sprite:create(""))
        :setAnchorPoint(cc.p(0,0.5))
        :setPosition(cc.p(bkposx,bkposy))
	    :setFontSize(28)
	  --  :setFontColor(cc.c3b(204,172,139))
	 --   :setPlaceholderFontColor(cc.c3b(204,172,139))
	 --   :setPlaceholderFontSize(28)
	    :setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
	    :setMaxLength(8)
	    :setPlaceHolder("输入结算金额")
    self.ly_bank:getChildByName("new_exchange_edit_bg_7"):addChild(self.bk_tf_exchangemount)

    self.bk_tf_exchangemount:registerScriptEditBoxHandler(function(event,editbox)
        if event == "return" then
            local nustr = editbox:getText()
            local money = tonumber(nustr)
			money = self:GoldMultiple(money)
            if money == nil or money < 0 then
                return 
            end
            if money * 1000 + LEFT_GOLD > GlobalUserItem.lUserScore then
                showToast(self, "账户金额不足", 1, cc.c3b(250, 0, 0))
                money = math.floor((GlobalUserItem.lUserScore-LEFT_GOLD)/ 1000)
				editbox:setText(tostring(money))
				local percent = 100
				self:refreshSubSlider(self.bk_slider_percent,percent*100)
			else

				editbox:setText(money)
				local percent = money / ((GlobalUserItem.lUserScore-LEFT_GOLD) / 1000)
				self:refreshSubSlider(self.bk_slider_percent,percent*100)
            end
        end
    end)
end



function ExchangeLayerNew:customEventHandler(event)
    if event.name == 'exchangeRecords' then
		self:dismissPopWait()
        self.ly_record:setVisible(true)
		GlobalUserItem.myExchangeRecords = event.data.list or {}
		GlobalUserItem.FreshExcahngeRecordsTime = os.time()
        self:handleRecords(event.data.list)
    elseif event.name == 'EXCHANGE' then
        showToast(self, event.data.msg, 1, cc.c3b(250, 0, 0))
		GlobalUserItem.FreshExcahngeRecordsTime = 0
        if event.data.result == 1 then
			self.bk_tf_exchangemount:setText("")
			self.ali_tf_exchangemount:setText("")
			self:refreshSubSlider(self.ali_slider_percent,0)
			self:refreshSubSlider(self.bk_slider_percent,0)
			local moneystr = ExternalFun.ChangeScore(GlobalUserItem.lUserScore - self.exgold,2,',')
			local reslt = string.gsub(moneystr,',','/')
			self.ali_txt_balance:setString(reslt)
			self.bk_txt_balance:setString(reslt)
			if self.veriCsnode then
				if self.schedulerID then
					cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.schedulerID)
				end
				self.veriCsnode:removeFromParent()
				self.veriCsnode = nil
				
			end
        end
    end
end

function ExchangeLayerNew:handleRecords(recordsData)

	self.records = recordsData or {}
	local templayer = self.ly_record:getChildByName("tableviewItem")
	if not self.recordTabView then
		self.recordTabView = cc.TableView:create(templayer:getContentSize())-- cc.size(993,518)
		self.recordTabView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
		self.recordTabView:setPosition(templayer:getPosition())--cc.p(18,50)  templayer:getPosition()
		self.recordTabView:setDelegate()
		self.recordTabView:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN)
		self.recordTabView:registerScriptHandler(handler(self, self.cellSizeForTable), cc.TABLECELL_SIZE_FOR_INDEX)
		self.recordTabView:registerScriptHandler(handler(self, self.tableCellAtIndex), cc.TABLECELL_SIZE_AT_INDEX)
		self.recordTabView:registerScriptHandler(handler(self, self.numberOfCellsInTableView), cc.NUMBER_OF_CELLS_IN_TABLEVIEW)
		templayer:getParent():addChild(self.recordTabView)
		templayer:removeFromParent()
		self.recordTabView:reloadData()
	else
		self.recordTabView:reloadData()
	end
	local needfresh = false
--[[	local intervalTime = os.time() - (GlobalUserItem.FreshExcahngeRecordsTime or 0)
	for k,v in pairs(self.records) do
		if v.status == 0 or v.status == 7 and  then
			needfresh = true
		end
	end
	GlobalUserItem.FreshExcahngeRecordsTime = needfresh --isFreshExcahngeRecords--]]
end	
function ExchangeLayerNew:cellSizeForTable( view, idx)
	return 997,53
end

function ExchangeLayerNew:tableCellAtIndex( view, idx)
	local cell = view:dequeueCell()
	local item = nil
	local itemdate = self.records[idx+1]
	if nil == cell then
		cell = cc.TableViewCell:new()
		item = self.ly_recordDemo:clone()
		item:setName("recorditem")
		item:setVisible(true)
		item:setPosition(0,0)
		cell:addChild(item)
		
	
		
	else
		item = cell:getChildByName("recorditem")
	end
	local txt_exway =  item:getChildByName("txt_exway")
	local txt_exnu =  item:getChildByName("txt_exnu")
	local txt_exmount =  item:getChildByName("txt_exmount")
	local txt_exdate =  item:getChildByName("txt_exdate")
	local txt_exstatus =  item:getChildByName("txt_exstatus")
	if itemdate.type == 1 then
		txt_exway:setString("支付宝")
	else
		txt_exway:setString("银行卡")
	end
	txt_exnu:setString(itemdate.orderid)
	txt_exdate:setString(itemdate.createtime)
	txt_exmount:setString(itemdate.gold/appdf.bili)
	if itemdate.status == 0 or itemdate.status == 7 then
		txt_exstatus:setString("正在处理")
		
	elseif  itemdate.status == 1  then
		txt_exstatus:setString("提现成功")
	elseif  itemdate.status == 2 or itemdate.status == 4   then
		txt_exstatus:setString("退款成功")
	elseif  itemdate.status == 3 or itemdate.status == 5 or itemdate.status == 6  then
		txt_exstatus:setString("提现失败")
	else
		txt_exstatus:setString("")
	end

	return cell
end
function ExchangeLayerNew:refreshSubSlider(slider,percent)
	percent = percent or slider:getPercent()
	percent = math.floor(percent+0.5)
	slider:setPercent(percent)
	local bg = slider:getChildByName("ats_bg")
	local slider_ats = bg:getChildByName("slider_ats")
	local sliderSize = slider:getContentSize()
	slider_ats:setString(percent.."/")
	bg:setPositionX(sliderSize.width *percent*0.01)
	
end
function ExchangeLayerNew:numberOfCellsInTableView(view)
	return #self.records
end

function ExchangeLayerNew:onButtonClicked(tag,ref)
    if ref == self.btn_close then
        self._scene:onKeyBack()
    elseif ref == self.btn_aplipayexchange then --支付宝兑换
        self:showLayer(1)
    elseif ref == self.btn_bankexchange then -- 银行卡兑换
        self:showLayer(2)
    elseif ref == self.btn_exchangerecord then --兑换记录
        self:showLayer(3)
    elseif ref == self.ali_btn_sure then    
        self:sendBindInfos(1)
    elseif ref == self.ali_btn_clear then
        self.ali_tf_exchangemount:setText("")

		self:refreshSubSlider(self.ali_slider_percent,0)
    elseif ref == self.ali_btn_max  then 
		self:refreshSubSlider(self.ali_slider_percent,100)
		local temp = GlobalUserItem.lUserScore-GlobalUserItem.exchangeConfig.limitgold
		temp = temp >= 0 and temp or 0
        local my = ExternalFun.ChangeScore(temp,2,',',false,true)
        local intmy = math.modf(my)
        self.ali_tf_exchangemount:setText(self:GoldMultiple(intmy))
    elseif ref == self.ali_btn_bindali then 
		if GlobalUserItem.accounttype == 0 then
		    showToast(self, "注册成为正式账号后即可绑定并结算现金！", 2)
		return
	end
        local alipay = AlipayLayer:create(self)
        self:addChild(alipay)
    elseif ref == self.bk_btn_sure then
        self:sendBindInfos(2)
    elseif ref == self.bk_btn_clear then 
        self.bk_tf_exchangemount:setText("")
		self:refreshSubSlider(self.bk_slider_percent,0)
    elseif ref == self.bk_btn_max then
        self:refreshSubSlider(self.bk_slider_percent,100)
		local temp = GlobalUserItem.lUserScore-GlobalUserItem.exchangeConfig.limitgold
		temp = temp >= 0 and temp or 0
        local my = ExternalFun.ChangeScore(temp,2,',',false,true)
        local intmy = math.modf(my)
        self.bk_tf_exchangemount:setText(self:GoldMultiple(intmy))
    elseif ref == self.bk_btn_bindcard then
		if GlobalUserItem.accounttype == 0 then
		showToast(self, "注册成为正式账号后即可绑定并结算现金！", 2)
		return
		end
        local banklayer = BindBankLayer:create(self)
        self:addChild(banklayer)
    end
end

function ExchangeLayerNew:openVerification(msg)
	self.schedulerID = nil
	local scheduler = cc.Director:getInstance():getScheduler()  
	local veriCsnode = ExternalFun.loadCSB("duihuang/VerificationLayer.csb",self)
	self.veriCsnode = veriCsnode
	local verificationbg_1 = veriCsnode:getChildByName("verificationbg_1")
	ExternalFun.playOpenLayerAnimation( verificationbg_1 )
	verificationbg_1:getChildByName("close"):addTouchEventListener(function(ref,type)
        if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect()
		  if self.schedulerID then
				cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.schedulerID)
		  end
			self.veriCsnode = nil
          veriCsnode:removeFromParent()
        end
    end)
	--账号输入
	local tempTextField = verificationbg_1:getChildByName("phone_TextField")
	local edit_Account = ccui.EditBox:create(tempTextField:getContentSize(), ccui.Scale9Sprite:create(""))
	:setPosition(tempTextField:getPosition())
	:setFontSize(tempTextField:getFontSize())
	:setMaxLength(11)
	:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
	:setPlaceHolder("请输入手机号")
	:addTo(tempTextField:getParent())
	tempTextField:removeFromParent()
	tempTextField = verificationbg_1:getChildByName("code_TextField")
	--验证码
	if GlobalUserItem.szAccount and GlobalUserItem.szAccount ~= "" then
		edit_Account:setText(GlobalUserItem.szAccount)
	end
	local  edit_code = ccui.EditBox:create(tempTextField:getContentSize(), ccui.Scale9Sprite:create(""))
	:setPosition(tempTextField:getPosition())
	:setFontSize(tempTextField:getFontSize())
	:setMaxLength(6)
	:setInputMode(cc.EDITBOX_INPUT_MODE_NUMERIC)
	:setPlaceHolder("请输入验证码")
	:addTo(tempTextField:getParent())
	tempTextField:removeFromParent()
	verificationbg_1:getChildByName("getcodebt"):addTouchEventListener( function(ref, type) --点击验证码按钮
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect()
			local AccountStr = string.gsub(edit_Account:getText()," ","")
			local codeStr = string.gsub(edit_code:getText()," ","")
			if AccountStr == ""  then
				showToast(self,"手机号不能为空",1)
				return
			end

			if  string.len(AccountStr) ~= 11 then
				showToast(self,"手机号长度错误",1)
				return
			end
			local pos = string.find(AccountStr,"1")
			if  not pos or pos ~= 1 then
				showToast(self,"手机号码错误",1)
				return
			end
			
            ref:setEnabled(false)
            local sec = 60
            ref:setTitleText("重发（" .. sec .. "）")

		   local autoCodecb = function(code,idx,verifycode,msg)
				self.codeidx = idx
			--	self.verifycode = verifycode
				showToast(self,msg or "发送失败",1)
			end


            local verityjson = {}
			verityjson.phone = AccountStr
			verityjson.userid = GlobalUserItem.dwUserID or 0
			verityjson.channelid = appdf.channelId
            utils.getVerityCode(verityjson,autoCodecb )
            self.schedulerID = scheduler:scheduleScriptFunc( function()
                sec = sec - 1
                if not tolua.isnull(ref) then
                    ref:setTitleText("重发（" .. sec .. "）")
                    if sec <= 0 then
                        cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.schedulerID)
                        ref:setEnabled(true)
                        ref:setTitleText("获取验证码")
                    end        
                end      
            end , 1, false)
        end
    end )
	verificationbg_1:getChildByName("sure_btn"):addTouchEventListener(function(ref,type)
        if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect()
			local AccountStr = string.gsub(edit_Account:getText()," ","")
			local codeStr = string.gsub(edit_code:getText()," ","")
			if AccountStr == "" or codeStr == ""  then
				showToast(self,"手机号或验证码不能为空",1)
				return
			end
			local tempcode = string.gsub(edit_code:getText()," ","") 
			msg.vidx = self.codeidx
			msg.verifycode = tonumber(tempcode)--self.verifycode
			self._scene._LogonFrame:sendBindInform(msg)
        end
    end)
end
--过长的*号显示
function ExchangeLayerNew:limitAcountLen(str)
	if not str or str == nil or str == "" then
		return ""
	end
	local preStr = string.sub(str,1,4)
	local lastStr = string.sub(str,-4,-1)
	return preStr.."**********"..lastStr

end
--btype  1:支付宝兑换 2:银行卡兑换
function ExchangeLayerNew:sendBindInfos(btype)
	if GlobalUserItem.accounttype == 0 then
		showToast(self, "注册账号后才可以进行结算操作", 2)
		return
	end

    local msg = {}
    msg.type = btype

    local exgold = 0
    local strmount = ""
    if btype == 1 then
		if not GlobalUserItem.szAliPayAcccount or GlobalUserItem.szAliPayAcccount == "" then
			showToast(self, "请完善绑定信息", 2)
			return 
		end
        strmount = string.rtrim( string.ltrim(self.ali_tf_exchangemount:getText()) )
    elseif btype == 2 then
		if not GlobalUserItem.bankid or GlobalUserItem.bankid == "" then
			showToast(self, "请完善绑定信息", 2)
			return 
		end
        strmount = string.rtrim( string.ltrim(self.bk_tf_exchangemount:getText()) )
    end

    if strmount == ""  or string.match(strmount,"[^%d]") then
        showToast(self, "请输入正确的结算数额, 大于零的整数额度", 2, cc.c3b(255, 255, 0))
        return 
    end

    exgold = tonumber(strmount)

    if exgold <= 0 then
        showToast(self, "请输入正确的结算数额, 大于零的整数额度", 2, cc.c3b(255, 255, 0))
        return
    end

    if exgold * appdf.bili > GlobalUserItem.lUserScore then
        showToast(self, "结算超过账户余额", 2, cc.c3b(255, 255, 0))
        return
    end

    if exgold * appdf.bili < GlobalUserItem.exchangeConfig.mingold then
        local ex,_ = math.modf((GlobalUserItem.exchangeConfig.mingold or 100000 )/appdf.bili)
        showToast(self, "结算最小额度 " .. tostring( ex) .. " 金币，至少保留"..GlobalUserItem.exchangeConfig.limitgold/appdf.bili.."金币" , 2, cc.c3b(255, 255, 0))
        return
    end
	if GlobalUserItem.lUserScore - exgold * appdf.bili < GlobalUserItem.exchangeConfig.limitgold then
		showToast(self, "结算后最低留存 " .. tostring( GlobalUserItem.exchangeConfig.limitgold/appdf.bili) .. " 金币" , 2, cc.c3b(255, 255, 0))
        return
	end
    msg.gold = exgold
    self.exgold = exgold*appdf.bili
	if GlobalUserItem.channelconfig.exchangesms == 1 then
		self:openVerification(msg)
	else
		self._scene._LogonFrame:sendBindInform(msg)
	end
   
end

--兑换金币倍数 转化 
function ExchangeLayerNew:GoldMultiple(gold)
	gold = tonumber(gold) or 0
	local multiple =GlobalUserItem.exchangeConfig.goldmultiple
	local exgold,other = math.modf(gold/multiple)
	return exgold*multiple
end
function ExchangeLayerNew:reSetBindingInfo(msg)
	if msg.type == 1 then
		self.ali_tf_cardnu:setString( msg.bindid)
		utils:LabelSetString(self.ali_tf_cardnu,self:limitAcountLen(msg.bindid) ,"暂未绑定支付宝账号")
		self.ali_btn_bindali:setVisible(false)
	elseif msg.type == 2 then
		self.bk_tf_cardnu:setString(msg.bindid)
		utils:LabelSetString(self.bk_tf_cardnu,self:limitAcountLen(msg.bindid),"暂未绑定银行卡账号")
		self.bk_btn_bindcard:setVisible(false)
	end
	
end
function ExchangeLayerNew:sendExchagneRecords()
	
    self._scene._LogonFrame:sendExchangeRecord(cc.UserDefault:getInstance():getIntegerForKey("exchangeMaxIdx", 0))
end



function ExchangeLayerNew:showLayer(idx)
    if idx > 3 or idx < 1 then
        self:showLayer(1)
        return
    end
	self.bk_tf_exchangemount:setText("")
	self.ali_tf_exchangemount:setText("")
	self:refreshSubSlider(self.ali_slider_percent,0)
	self:refreshSubSlider(self.bk_slider_percent,0)
    if idx == 1 then
        self.ly_alipay:setVisible(true)
        self.ly_bank:setVisible(false)
        self.ly_record:setVisible(false)
		if self.btn_aplipayexchange then
			self.btn_aplipayexchange:setEnabled(false)
		end
		
		if self.btn_bankexchange then
			self.btn_bankexchange:setEnabled(true) 
		end
		self.btn_exchangerecord:setEnabled(true)
		
        self.currentPage = 1
    elseif idx == 2 then
        self.ly_alipay:setVisible(false)
        self.ly_bank:setVisible(true)
        self.ly_record:setVisible(false)
		if self.btn_aplipayexchange then
			self.btn_aplipayexchange:setEnabled(true)
		end
		
		if self.btn_bankexchange then
			self.btn_bankexchange:setEnabled(false) 
		end
		self.btn_exchangerecord:setEnabled(true)
        self.currentPage = 2
    elseif idx == 3 then
        if self.currentPage == 3 then
            return
        end
        self.currentPage = 3
        self.ly_alipay:setVisible(false)
        self.ly_bank:setVisible(false)
        self.ly_record:setVisible(true)
		if self.btn_aplipayexchange then
			self.btn_aplipayexchange:setEnabled(true)
		end
		
		if self.btn_bankexchange then
			self.btn_bankexchange:setEnabled(true) 
		end
		
		local intervalTime = os.time() - (GlobalUserItem.FreshExcahngeRecordsTime or 0)
		self.btn_exchangerecord:setEnabled(false)
		if GlobalUserItem.myExchangeRecords == nil or intervalTime > 30 then
			self:sendExchagneRecords()
			self:showPopWait()
		else
			self:handleRecords(GlobalUserItem.myExchangeRecords)
		end
        
    end
end
--显示等待
function ExchangeLayerNew:showPopWait()
	self._scene:showPopWait()
end

--关闭等待
function ExchangeLayerNew:dismissPopWait()
	self._scene:dismissPopWait()
end
return ExchangeLayerNew 